namespace SubhadraSolutions.Sharp.Logging.LogSubscribers.FileSystem
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Text;

    public abstract class AbstractFileLogSubscriber : AbstractFileLogSubscriberCore
    {
        #region Constructors

        protected AbstractFileLogSubscriber()
        {
            Encoding = Encoding.ASCII;
        }

        #endregion Constructors

        #region Properties

        public Encoding Encoding
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        protected override void createNewFile()
        {
            bool isNewFile;
            StreamWriter writer = getFileWriter(out isNewFile);
            if (writer != null)
            {
                writer.Close();
            }
        }

        protected virtual StreamWriter getFileWriter(out bool isNewFile)
        {
            isNewFile = false;
            try
            {
                StreamWriter writer;
                if (onlyAppendMode)
                {
                    _writingFileInfo.Refresh();
                    if (!_writingFileInfo.Exists)
                    {
                        isNewFile = true;
                    }
                    writer = Encoding == null
                        ? (new StreamWriter(_writingFileInfo.FullName, true))
                        : (new StreamWriter(_writingFileInfo.FullName, true, Encoding));
                }
                else
                {
                    FileStream fs = File.Open(_writingFileInfo.FullName, FileMode.OpenOrCreate,
                        FileAccess.Write);
                    isNewFile = fs.Length < newFileSizeThreshold;
                    fs.Seek(0, SeekOrigin.End);
                    writer = Encoding == null
                        ? (new StreamWriter(fs))
                        : (new StreamWriter(fs, Encoding));
                }
                writer.AutoFlush = AutoFlush;
                return writer;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            return null;
        }

        protected abstract void publishLogs(StreamWriter writer, IEnumerable<LogStoreItem> e,
            bool isNewFile);

        protected override void writeInfoFile(IEnumerable<LogStoreItem> e)
        {
            bool isNewFile;
            StreamWriter writer = getFileWriter(out isNewFile);
            if (writer != null)
            {
                publishLogs(writer, e, isNewFile);
                writer.Close();
            }
        }

        #endregion Methods
    }
}